package petrochina.company.electric.ui.dialog;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.toast.ToastUtils;
import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.inuker.bluetooth.library.utils.BluetoothLog;
import com.tencent.mmkv.MMKV;
import com.ut.ble.BleDevice;
import com.ut.ble.scan.IScanCallback;
import com.ut.blelock.BleLockController;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import petrochina.company.electric.R;
import petrochina.company.electric.aop.SingleClick;
import petrochina.company.electric.app.AppAdapter;
import petrochina.company.electric.http.api.BleDeviceListApi;
import petrochina.company.electric.http.api.TaskDetailStepApi;
import petrochina.company.electric.listener.OnDeviceSearchListener;
import petrochina.company.electric.manager.ClientManager;

/**
 * 优特蓝牙设备搜索 连接 操作
 */
public final class BleDeviceSearchDialog {

    public static final class Builder
            extends BaseDialog.Builder<Builder>
            implements BaseAdapter.OnChildClickListener,
            View.OnLayoutChangeListener, Runnable {

        @SuppressWarnings("rawtypes")
        @Nullable
        private OnListener mListener;
        private boolean mAutoDismiss = true;

        private static final int START_DISCOVERY = 0x08;
        private static final int STOP_DISCOVERY = 0x09;
        private static final int DISCOVERY_DEVICE = 0x0A;
        private static final int DISCOVERY_OUT_TIME = 0x0B;
        private static final int BT_OPENED = 0x0D;
        private static final int BT_CLOSED = 0x0E;
        private BLEBroadcastReceiver bleBroadcastReceiver;

        private final RecyclerView mRecyclerView;
        private final AppCompatImageView mCancelView;
        private final AppCompatButton mSearchView;
        private final AppCompatTextView mTvSearchTitle;

        private final BleDevicesAdapter mAdapter;
        private Context mContext;

        private TaskDetailStepApi.Bean mTaskPowerResult;
        private BluetoothAdapter bluetoothAdapter;
        //扫描结果回调
//        private OnDeviceSearchListener onDeviceSearchListener = new OnDeviceSearchListener() {
//
//            @Override
//            public void onDeviceFound(BleDeviceListApi.Bean bean) {
//                Message message = new Message();
//                message.what = DISCOVERY_DEVICE;
//                message.obj = bean;
//                mHandler.sendMessage(message);
//            }
//
//            @Override
//            public void onDiscoveryOutTime() {
//                Message message = new Message();
//                message.what = DISCOVERY_OUT_TIME;
//                mHandler.sendMessage(message);
//            }
//        };

//        /**
//         * 注册广播
//         */
//        private void initBLEBroadcastReceiver() {
//            if (bleBroadcastReceiver != null) {
//                return;
//            }
//            //注册广播接收
//            bleBroadcastReceiver = new BLEBroadcastReceiver();
//            IntentFilter intentFilter = new IntentFilter();
//            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); //开始扫描
//            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//扫描结束
//            intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//手机蓝牙状态监听
//            mContext.registerReceiver(bleBroadcastReceiver, intentFilter);
//        }

        private Handler mHandler = new Handler() {
            @SuppressLint("SetTextI18n")
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case START_DISCOVERY:
                        Log.d("TAG", "开始搜索设备...");
                        break;

                    case STOP_DISCOVERY:
                        Log.d("TAG", "停止搜索设备...");
                        break;

                    case DISCOVERY_DEVICE:  //扫描到设备
                        BleDeviceListApi.Bean bleDevice = (BleDeviceListApi.Bean) msg.obj;
                        if (!mAdapter.getData().contains(bleDevice)) {
                            mAdapter.addItem(bleDevice);
                        }

                        break;

//                    case SELECT_DEVICE:
//                        BluetoothDevice bluetoothDevice = (BluetoothDevice) msg.obj;
//                        tvName.setText(bluetoothDevice.getName());
//                        tvAddress.setText(bluetoothDevice.getAddress());
//                        curBluetoothDevice = bluetoothDevice;
//                        break;
//
//                    case CONNECT_FAILURE: //连接失败
//                        Log.d(TAG, "连接失败");
//                        tvCurConState.setText("连接失败");
//                        curConnState = false;
//                        break;
//
//                    case CONNECT_SUCCESS:  //连接成功
//                        Log.d(TAG, "连接成功");
//                        tvCurConState.setText("连接成功");
//                        curConnState = true;
//                        llDataSendReceive.setVisibility(View.VISIBLE);
//                        llDeviceList.setVisibility(View.GONE);
//                        break;
//
//                    case DISCONNECT_SUCCESS:
//                        Log.d(TAG, "断开成功");
//                        tvCurConState.setText("断开成功");
//                        curConnState = false;
//
//                        break;
//
//                    case SEND_FAILURE: //发送失败
//                        byte[] sendBufFail = (byte[]) msg.obj;
//                        String sendFail = TypeConversion.bytes2HexString(sendBufFail,sendBufFail.length);
//                        tvSendResult.setText("发送数据失败，长度" + sendBufFail.length + "--> " + sendFail);
//                        break;
//
//                    case SEND_SUCCESS:  //发送成功
//                        byte[] sendBufSuc = (byte[]) msg.obj;
//                        String sendResult = TypeConversion.bytes2HexString(sendBufSuc,sendBufSuc.length);
//                        tvSendResult.setText("发送数据成功，长度" + sendBufSuc.length + "--> " + sendResult);
//                        break;
//
//                    case RECEIVE_FAILURE: //接收失败
//                        String receiveError = (String) msg.obj;
//                        tvReceive.setText(receiveError);
//                        break;
//
//                    case RECEIVE_SUCCESS:  //接收成功
//                        byte[] recBufSuc = (byte[]) msg.obj;
//                        String receiveResult = TypeConversion.bytes2HexString(recBufSuc,recBufSuc.length);
//                        tvReceive.setText("接收数据成功，长度" + recBufSuc.length + "--> " + receiveResult);
//                        break;

                    case BT_CLOSED:
                        Log.d("TAG", "系统蓝牙已关闭");
                        break;

                    case BT_OPENED:
                        Log.d("TAG", "系统蓝牙已打开");
                        break;
                }

            }
        };

        /**
         * 蓝牙广播接收器
         */
        private class BLEBroadcastReceiver extends BroadcastReceiver {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (TextUtils.equals(action, BluetoothAdapter.ACTION_DISCOVERY_STARTED)) { //开启搜索
                    Message message = new Message();
                    message.what = START_DISCOVERY;
                    mHandler.sendMessage(message);

                } else if (TextUtils.equals(action, BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {//完成搜素
                    Message message = new Message();
                    message.what = STOP_DISCOVERY;
                    mHandler.sendMessage(message);

                } else if (TextUtils.equals(action, BluetoothAdapter.ACTION_STATE_CHANGED)) {   //系统蓝牙状态监听

                    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    if (state == BluetoothAdapter.STATE_OFF) {
                        Message message = new Message();
                        message.what = BT_CLOSED;
                        mHandler.sendMessage(message);

                    } else if (state == BluetoothAdapter.STATE_ON) {
                        Message message = new Message();
                        message.what = BT_OPENED;
                        mHandler.sendMessage(message);

                    }
                }
            }
        }


        public Builder(Context context, int equipType) {
            super(context);
            mContext = context;
            setContentView(R.layout.ble_search_dialog);
            setAnimStyle(BaseDialog.ANIM_BOTTOM);
            setHeight(getResources().getDisplayMetrics().heightPixels * 2 / 3);
            mRecyclerView = findViewById(R.id.rv_ble_list);
            mCancelView = findViewById(R.id.iv_ble_search_closer);
            mTvSearchTitle = findViewById(R.id.tv_search_title);
            mSearchView = findViewById(R.id.btn_dialog_search);
            setOnClickListener(mCancelView, mSearchView);

            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//            mTvSearchTitle.setText(equipType == 3 ? "请选择你的 [接地极] 设备连接" : "请选择你的 [验电棒] 设备连接");
            mTvSearchTitle.setText("读取设备");
            mAdapter = new BleDevicesAdapter(getContext());
            mAdapter.setOnChildClickListener(R.id.btn_connect_state, this);
            mRecyclerView.setAdapter(mAdapter);
            mAdapter.setData(new ArrayList<>());
//            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
//            context.registerReceiver(receiver, filter);
            initData();
//            mContext.unregisterReceiver(receiver);
//            initBLEBroadcastReceiver();
        }

        private void initData() {

        }

        @Override
        public void show() {
            super.show();
//            mAdapter.clearData();
//            getConnectedBtDevice();
            scanBleDevice();
//            if (mTaskPowerResult!= null){
//                if (mTaskPowerResult.getEquipType() == 3) {
//                    if (!TextUtils.isEmpty(mTaskPowerResult.getEquipValue())) {
//                        mTvSearchTitle.setText("预期电阻值：" + mTaskPowerResult.getEquipValue() + "欧姆");
//                    }
//                }else{
//                    mTvSearchTitle.setText("预期带电状态：" + (mTaskPowerResult.getOperType() == 3 ? "带电" : "不带电"));
//                }
//            }
        }

        protected void scanBleDevice() {
            //查找蓝牙设备
            SearchRequest request = new SearchRequest.Builder()
                    .searchBluetoothLeDevice(7000, 3)// 先扫BLE设备3次，每次7s
//                    .searchBluetoothClassicDevice(5000)
//                    .searchBluetoothLeDevice(2000)
                    .build();

            ClientManager.getClient().search(request, new SearchResponse() {
                @Override
                public void onSearchStarted() {

                }

                @Override
                public void onDeviceFounded(SearchResult device) {
                    Beacon beacon = new Beacon(device.scanRecord);
                    BleDeviceListApi.Bean bean = verifyAndGetDevice(device.getName(),device.getAddress());
//                    BleDeviceListApi.Bean bean = new BleDeviceListApi.Bean();
//                    bean.setName(device.getName());
                    Log.d("TAG", device.getName() + "-->" + device.getAddress());
//                    bean.setBluetookthAddress(device.getAddress());
                    if (bean != null) {
                        if (mAdapter.getData() != null) {
                            if (mAdapter.getData().contains(bean)) {
                                return;
                            }
                        }
                        mAdapter.addItem(bean);
                        String name = device.getName();
//                        BluetoothLog.v(String.format("beacon for %s\n%s", device.getAddress(), beacon.toString()));
                    }
                }

                @Override
                public void onSearchStopped() {

                }

                @Override
                public void onSearchCanceled() {

                }
            });
//            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//            bluetoothAdapter.startDiscovery();

//            startDiscoveryDevice(onDeviceSearchListener, 15000);
        }

//        ////////////////////////////////////  扫描设备  ///////////////////////////////////////////////
//        //扫描设备回调
//        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
//        private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
//            @Override
//            public void onLeScan(BluetoothDevice bluetoothDevice, int rssi, byte[] bytes) {
//                //在onLeScan()回调中尽量做少的操作，可以将扫描到的设备扔到另一个线程中处理
//                if (bluetoothDevice == null)
//                    return;
//
//                if (bluetoothDevice.getName() != null) {
//                    Log.d("TAG", bluetoothDevice.getName() + "-->" + bluetoothDevice.getAddress());
////                } else {
////                    Log.d("TAG", "null" + "-->" + bluetoothDevice.getAddress());
//                }
////                BleDeviceListApi.Bean bean = new BleDeviceListApi.Bean();
////                bean.setName(bluetoothDevice.getName());
////                bean.setBluetookthAddress(bluetoothDevice.getAddress());
//                BleDeviceListApi.Bean bean = verifyAndGetDevice(bluetoothDevice);
////                BLEDevice bleDevice = new BLEDevice(bluetoothDevice, rssi);
//                if (bean != null && onDeviceSearchListener != null) {
//                    onDeviceSearchListener.onDeviceFound(bean);  //扫描到设备回调
//                }
//            }
//        };
//
//        //获取已连接的蓝牙设备
//        private void getConnectedBtDevice(){
//            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
//            Class<BluetoothAdapter> bluetoothAdapterClass = BluetoothAdapter.class;//得到BluetoothAdapter的Class对象
//            try {
//                //得到连接状态的方法
//                Method method = bluetoothAdapterClass.getDeclaredMethod("getConnectionState", (Class[]) null);
//                //打开权限
//                method.setAccessible(true);
//                int state = (int) method.invoke(adapter, (Object[]) null);
//                if(state == BluetoothAdapter.STATE_CONNECTED){
//                    Log.i("TAG11111111","BluetoothAdapter.STATE_CONNECTED");
//                    Set<BluetoothDevice> devices = adapter.getBondedDevices(); //集合里面包括已绑定的设备和已连接的设备
//                    Log.i("TAG11111111","devices:"+devices.size());
//                    for(BluetoothDevice device : devices){
//                        Method isConnectedMethod = BluetoothDevice.class.getDeclaredMethod("isConnected", (Class[]) null);
//                        method.setAccessible(true);
//                        boolean isConnected = (boolean) isConnectedMethod.invoke(device, (Object[]) null);
//                        if(isConnected){ //根据状态来区分是已连接的还是已绑定的，isConnected为true表示是已连接状态。
//                            Log.i("TAG11111111","connected:"+device.getName());
//                            //deviceList.add(device);
//                        }
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//
//        /**
//         * 设置时间段 扫描设备
//         *
//         * @param onDeviceSearchListener 设备扫描监听
//         * @param scanTime               扫描时间
//         */
//        public void startDiscoveryDevice(OnDeviceSearchListener onDeviceSearchListener, long scanTime) {
//            if (bluetoothAdapter == null) {
//                Log.e("TAG", "startDiscoveryDevice-->bluetooth4Adapter == null");
//                return;
//            }
//
//            this.onDeviceSearchListener = onDeviceSearchListener;
//
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
//                Log.d("TAG", "开始扫描设备");
//                bluetoothAdapter.startLeScan(leScanCallback);
//
//            } else {
//                return;
//            }
//
//            //设定最长扫描时间
//            mHandler.postDelayed(stopScanRunnable, scanTime);
//        }
//
//        private Runnable stopScanRunnable = new Runnable() {
//            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
//            @Override
//            public void run() {
//                if (onDeviceSearchListener != null) {
//                    onDeviceSearchListener.onDiscoveryOutTime();  //扫描超时回调
//                }
//                //scanTime之后还没有扫描到设备，就停止扫描。
//                stopDiscoveryDevice();
//            }
//        };
//
//        //////////////////////////////////////  停止扫描  /////////////////////////////////////////////
//
//        /**
//         * 停止扫描
//         */
//        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
//        public void stopDiscoveryDevice() {
//            mHandler.removeCallbacks(stopScanRunnable);
//
//            if (bluetoothAdapter == null) {
//                Log.e("TAG", "stopDiscoveryDevice-->bluetooth4Adapter == null");
//                return;
//            }
//
//            if (leScanCallback == null) {
//                Log.e("TAG", "stopDiscoveryDevice-->leScanCallback == null");
//                return;
//            }
//
//            Log.d("TAG", "停止扫描设备");
//            bluetoothAdapter.stopLeScan(leScanCallback);
//        }

        // Create a BroadcastReceiver for ACTION_FOUND.
//        private final BroadcastReceiver receiver = new BroadcastReceiver() {
//            public void onReceive(Context context, Intent intent) {
//                String action = intent.getAction();
//                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//                    // Discovery has found a device. Get the BluetoothDevice
//                    // object and its info from the Intent.
//                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//                    if (device.getName() == null) {
//                        return;
//                    }
//                    String deviceName = device.getName();
//                    String deviceHardwareAddress = device.getAddress(); // MAC address
//                    BleDeviceListApi.Bean bean = new BleDeviceListApi.Bean();
//                    bean.setName(device.getName());
//                    bean.setBluetookthAddress(device.getAddress());
//                    if (bean != null) {
//                        if (mAdapter.getData() != null) {
//                            if (mAdapter.getData().contains(bean)) {
//                                return;
//                            }
//                        }
//                        mAdapter.addItem(bean);
//                        String name = device.getName();
//                    }
//                }
//            }
//        };

        /**
         * 根据equipType校验设备并返回实例2：验电棒 3：接地级
         */
        private BleDeviceListApi.Bean verifyAndGetDevice(String name,String address) {
            if (TextUtils.isEmpty(name) || "NULL".equals(name)) {
                return null;
            }
            if (mTaskPowerResult == null) {
                return null;
            } else {
                MMKV mmkv = MMKV.defaultMMKV();
                Gson gson = new Gson();
                List<BleDeviceListApi.Bean> devicesList = null;
                String listJson = null;
                switch (mTaskPowerResult.getEquipType()) {
                    case 2:
                        listJson = mmkv.getString("bleDevices2Json", null);
                        break;
                    case 3:
                        listJson = mmkv.getString("bleDevices3Json", null);
                        break;
                    case 4:
                        listJson = mmkv.getString("bleDevices4Json", null);
                        break;
                }
                if (TextUtils.isEmpty(listJson)) {
                    return null;
                }
                devicesList = gson.fromJson(listJson, new TypeToken<List<BleDeviceListApi.Bean>>() {
                }.getType());
                if (devicesList == null || devicesList.size() == 0) {
                    return null;
                }
                BleDeviceListApi.Bean bean = new BleDeviceListApi.Bean();
                bean.setBluetookthAddress(address);
                // 判断该设备是否存在于设备列表中
                if (!devicesList.contains(bean)) {
                    return null;
                } else {
                    return devicesList.get(devicesList.indexOf(bean));
                }
            }
        }

        protected void stopScanBleDevice() {
            //停止查找蓝牙设备
            ClientManager.getClient().stopSearch();
//            mContext.unregisterReceiver(receiver);
//            mContext.unregisterReceiver(bleBroadcastReceiver);
//            stopDiscoveryDevice();
        }

        @Override
        public Builder setGravity(int gravity) {
            switch (gravity) {
                // 如果这个是在中间显示的
                case Gravity.CENTER:
                case Gravity.CENTER_VERTICAL:
                    // 不显示取消按钮
                    setCancel(null);
                    // 重新设置动画
                    setAnimStyle(BaseDialog.ANIM_SCALE);
                    break;
                default:
                    break;
            }
            return super.setGravity(gravity);
        }

        @Override
        public Builder addOnDismissListener(@NonNull BaseDialog.OnDismissListener listener) {
            return super.addOnDismissListener(listener);
        }

        public Builder setList(int... ids) {
            List<String> data = new ArrayList<>(ids.length);
            for (int id : ids) {
                data.add(getString(id));
            }
            return setList(data);
        }

        public Builder setList(String... data) {
            return setList(Arrays.asList(data));
        }

        public BleDeviceSearchDialog.Builder setData(TaskDetailStepApi.Bean taskPowerResult) {
            this.mTaskPowerResult = taskPowerResult;
            return this;
        }

        @SuppressWarnings("all")
        public Builder setList(List data) {
            mAdapter.setData(data);
            mRecyclerView.addOnLayoutChangeListener(this);
            return this;
        }

        public Builder setCancel(@StringRes int id) {
            return setCancel(getString(id));
        }

        public Builder setCancel(CharSequence text) {
            //隐藏
//            mCancelView.setText(text);
            return this;
        }

        public Builder setAutoDismiss(boolean dismiss) {
            mAutoDismiss = dismiss;
            return this;
        }

        @SuppressWarnings("rawtypes")
        public Builder setListener(OnListener listener) {
            mListener = listener;
            return this;
        }

        @Override
        public void dismiss() {
//            mContext.unregisterReceiver(receiver);
//            mContext.unregisterReceiver(bleBroadcastReceiver);
            super.dismiss();
        }

        @SingleClick
        @Override
        public void onClick(View view) {
            if (mAutoDismiss) {
//                stopScanBleDevice();
                dismiss();
            }

            if (view == mCancelView) {
//                stopScanBleDevice();
                if (mListener == null) {
                    return;
                }
                mListener.onCancel(getDialog());
            }
            if (view == mSearchView) {
//                stopScanBleDevice();
                scanBleDevice();
            }
        }

        /**
         * {@link View.OnLayoutChangeListener}
         */
        @Override
        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
            mRecyclerView.removeOnLayoutChangeListener(this);
            // 这里一定要加延迟，如果不加在 Android 9.0 上面会导致 setLayoutParams 无效
            post(this);
        }

        @Override
        public void run() {
            final ViewGroup.LayoutParams params = mRecyclerView.getLayoutParams();
            final int maxHeight = getScreenHeight() / 4 * 3;
            if (mRecyclerView.getHeight() > maxHeight) {
                if (params.height != maxHeight) {
                    params.height = maxHeight;
                    mRecyclerView.setLayoutParams(params);
                }
                return;
            }

            if (params.height != ViewGroup.LayoutParams.WRAP_CONTENT) {
                params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                mRecyclerView.setLayoutParams(params);
            }
        }

        /**
         * 获取屏幕的高度
         */
        private int getScreenHeight() {
            Resources resources = getResources();
            DisplayMetrics outMetrics = resources.getDisplayMetrics();
            return outMetrics.heightPixels;
        }

        @Override
        public void onChildClick(RecyclerView recyclerView, View childView, int position) {
            if (mAutoDismiss) {
                dismiss();
            }
            if (mListener == null) {
                return;
            }
            List<BleDeviceListApi.Bean> list = mAdapter.getData();
            mListener.onSelected(getDialog(), position, mAdapter.getItem(position));
            stopScanBleDevice();
        }
    }

    private static final class BleDevicesAdapter extends AppAdapter<BleDeviceListApi.Bean> {

        private BleDevicesAdapter(Context context) {
            super(context);
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder();
        }

        private final class ViewHolder extends AppAdapter<?>.ViewHolder {

            private final TextView tvDeviceName;
            private final TextView tvMac;

            private final AppCompatButton btnConnectState;

            ViewHolder() {
                super(R.layout.ble_search_item);
                tvDeviceName = findViewById(R.id.tv_device_name);
                tvMac = findViewById(R.id.tv_mac);
                btnConnectState = findViewById(R.id.btn_connect_state);
            }

            @Override
            public void onBindView(int position) {
                BleDeviceListApi.Bean result = getItem(position);
                tvDeviceName.setText(result.getName());
                tvMac.setText("编号：" + result.getCode());
            }
        }
    }

    public interface OnListener<T> {

        /**
         * 选择条目时回调
         */
        void onSelected(BaseDialog dialog, int position, T t);

        /**
         * 点击取消时回调
         */
        default void onCancel(BaseDialog dialog) {
        }
    }

}